<template>
  <div>
     <div class="title_wrap">
        <h1>文章管理</h1>
        <el-button type="primary" @click="open">发布文章</el-button>
     </div>

     <div class="search_wrap">
        <el-form inline   label-width="120px">
          <el-form-item label="文章分类："  style="width:400px;">
             <el-select v-model="formQuery.cate_id">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id">{{item.cate_name}}</el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="发布状态：" style="width:400px;">
             <el-select v-model="formQuery.state">
                 <el-option value="已发布">已发布</el-option>
                 <el-option value="草稿">草稿</el-option>
             </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSearch"> 搜索</el-button>
             <el-button>重置</el-button>
          </el-form-item>
        </el-form>
     </div>
     <div>
        <el-table border :data="articleList">
            <el-table-column label="文章标题" prop="title"></el-table-column>
            <el-table-column label="文章分类" prop="cate_name"></el-table-column>
            <el-table-column label="发表时间" prop="title">
              <template #default="{row}">
                <div>
                  {{new Date(row.pub_date).toLocaleDateString()}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="state"></el-table-column>
              <el-table-column label="操作" prop="title">
                <template #default="{row}">
                  <div>
                      <el-button  type="primary" @click="toEdit(row.id)" circle :icon="Edit"></el-button>
                       <el-button type="danger" @click="toDel(row.id)" circle :icon="Delete"></el-button>
                  </div>
                </template>
              </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: flex-end;">
         <el-pagination  background layout="prev,pager,next,sizes" :total="total" :page-sizes="[1,2,3,4,5]" @current-change="pageChange"
         @size-change="sizeChange"></el-pagination>
        </div>
     </div>
     
      <el-drawer
        v-model="drawer"
        title="添加文章"
        size="50%"
       
      >
         <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px"> 
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addForm.title"></el-input>
          </el-form-item>
           <el-form-item label="文章分类" prop="cate_id">
              <el-select v-model="addForm.cate_id">
                <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id">{{item.cate_name}}</el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <el-upload
                class="avatar-uploader"
              
                :show-file-list="false"
                :on-change="handleChange"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
          </el-form-item>
          <el-form-item label="文章内容" prop='content'>
             <!-- 常见三种 富文本tinymce vue-quill-editor wangeditor -->
              <wangEditor height="300px" v-model:content="addForm.content"></wangEditor>

          </el-form-item>
          <el-form-item>
             <el-button type="primary" @click="toAdd('已发布')">发布</el-button>
             <el-button type="danger"  @click="toAdd('草稿')">草稿</el-button>
          </el-form-item>
         </el-form>
  


      </el-drawer>

  </div>
</template>
<script setup lang="ts">
import {Edit,Delete,Plus} from '@element-plus/icons-vue'
import wangEditor from '@/components/wangEditor.vue'
import {reactive,watch} from 'vue'
import {getCateList} from '@/api/newscate'
import {artPublishService,artGetListService,artDelService,artGetDetailService,artEditService} from '@/api/newslist'
import type {UploadFile,UploadFiles,FormInstance} from 'element-plus'
import {ElMessage} from 'element-plus'

// npm install @wangeditor/editor --save
// npm install @wangeditor/editor-for-vue@next --save


import {ref,shallowRef,onBeforeUnmount} from 'vue'
 let drawer=ref<boolean>(false);
 let imageUrl=ref('')
let open=()=>{
  drawer.value=true;
   addForm.content=''
}
// 获取文章分类列表 分类下拉框
interface Icate{
  cate_name:string,
  cate_alias:string,
  id:number
}
let cateList=ref<Icate[]>([]);
let getCate=async ()=>{
  let res=await getCateList();
  cateList.value=res.data;
}
getCate()
// 添加需要的数据
interface Iadd{
  title:string,
  cate_id:number|string,
  content:string,
  cover_img:Blob|null,
  state:string,
  id?:number
}
let addForm=reactive<Iadd>({
  title:"",//标题
  cate_id:"",//分类id
  cover_img:null,//封面
  content:"舒服哈舒服啥地方地方撒发生",//富文本的值
  state:"",//状态
})

// 选择文章 
let handleChange=(uploadFile: UploadFile, uploadFiles: UploadFiles):void=>{
     console.log(Object.prototype.toString.call(uploadFile.raw)) //文件的流
    imageUrl.value=URL.createObjectURL(uploadFile.raw!)
    // 类型断言
    addForm.cover_img=uploadFile.raw as Blob

}

// 规则
let rules={
  title:[{required:true,message:"请输入标题",trigger:"blur"}],
  cate_id:[{required:true,message:"请选择分类",trigger:"change"}],
  cover_img:[{required:true,message:"请上传封面",trigger:"change"}],
  content:[{required:true,message:"请输入内容",trigger:"blur"}],
}
let addFormRef=ref<FormInstance>()
// 添加功能
let toAdd=(state:string)=>{
  addForm.state=state
   let formdata=new FormData();
  //  
   for(let key in addForm){
     formdata.append(key,addForm[key])
   }
   addFormRef.value?.validate(async (vali:boolean)=>{
    if(vali){
      // 添加接口
      if(addForm.id){
          let editRes=await artEditService(formdata)
          ElMessage.success("修改成功")
      }else{
         let res=await  artPublishService(formdata)
        console.log(res,"--------------")
            ElMessage.success("添加成功")
      }
       
        addFormRef.value?.resetFields()
    
          getlist();
        imageUrl.value=""
        drawer.value=false//关闭弹出
    }

   })
  
}


// 文章列表-----------------------------------------------
let formQuery=reactive({
   pagenum:1,
   pagesize:5,
   cate_id:"",
   state:""
})
let articleList=ref([])//文章列表
let total=ref(0)//数据总条数
let getlist=async ()=>{
  let res=await artGetListService(formQuery)
  console.log(res,"文章列表数据")
  articleList.value=res.data;
  total.value=res.total;// 总条数
}
getlist()
// 搜索
let toSearch=()=>{
  getlist()
  formQuery.cate_id=""
  formQuery.state=""
}
// 分页
let pageChange=(val:number)=>{
 formQuery.pagenum=val;
  getlist()
}
// 每页条数的改变事件
let sizeChange=(val:number)=>{
  formQuery.pagesize=val;
  getlist()
}
// 删除接口-------------------------------------------------
let toDel=async (id:number)=>{
  let res=await artDelService(id);
  ElMessage.success("删除成功")
  getlist();
}
// 编辑回显------------------------------------------------------
let toEdit=async (id:number)=>{
  let res=await artGetDetailService(id)
  console.log(res,"-------------")
  drawer.value=true;
  imageUrl.value="http://big-event-vue-api-t.itheima.net"+res.data.cover_img;
  addForm=res.data; //回显的数据 都赋值给了addForm
}

// 监听弹出层关闭
watch(drawer,(val)=>{
  if(!val){
    addForm.cate_id=''
    addForm.content=''
    addForm.title=''
  }
})


</script>
<style lang="scss">
  .title_wrap{
     display: flex;
     justify-content: space-between;
     align-items: center;
     margin-bottom: 20px;
     background: white;
  }
  .search_wrap{
     margin-bottom: 20px;
     background: white;
  }
  .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
  .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
